<?php
// vim: set filetype=php expandtab tabstop=2 shiftwidth=2 autoindent smartindent:

function googtube_help($path, $arg) {
  switch ($path) {
    case 'admin/help#googtube':
      $output = '<p>'. t('Googtube is a filter module that automatically converts Youtube and Vimeo video urls into embedded code. Useful if users want to post videos easily.') .'</p>';
      $output .= t('<p>Use Input Formats to enable the googtube filter</p>
<ol>
<li>Select an existing Input Format or add a new one</li>
<li>Configure the Input Format</li>
<li>Enable googtube filter and Save configuration</li>
<li>Rearrange the weight of the googtube filter depending on what filters exist in the format. (Before Url Filter and after HTML works for me)</li>
</ol>');
      $output .= '<p>'. t('You can enable the googtube filter in an input format from <a href="/admin/config/content/formats" />admin/config/content/formats</a>') .'</p>';
      return $output;
  }
}

/**
 * Implement hook_filter_info().
 */
function googtube_filter_info() {
  $filters['googtube'] = array(
    'title' => t('Googtube filter'),
    'description' => t('Googtube is a filter module that automatically converts Youtube and Vimeo video urls into embedded code. Useful if users want to post videos easily.'),
    'process callback' => '_googtube_process',
    'settings callback' => '_googtube_settings',
    'default settings' => array(
      'googtube_method'=> 'embedded',
      'googtube_width' => '425',
      'googtube_height' => '344',
      'googtube_info_hw' => 1,
      'googtube_fs' => 0,
      'googtube_autoplay' => 0,
      'googtube_rel' => 1,
      'googtube_removed' => 1,
    ),
    'tips callback' => '_googtube_tips',
  );
  return $filters;
}

function _googtube_settings($form, &$form_state, $filter, $format, $defaults, $filters) {
  $methods = array(
    'embedded' => t('Embedded'),
	'iframe' => t('Iframe'),
  );
  // check is colorbox module installed
  if (module_exists('colorbox')) {
    $methods = $methods + array('colorbox'=> t('Colorbox'));
  }
  // check if floatbox module installed
  if (module_exists('floatbox')) {
    $methods = $methods + array('floatbox'=> t('Floatbox'));
  }
  // all possible parameters
  $settings['googtube_method'] = array(
    '#type' => 'select',
    '#title' => t('Method to show video'),
    '#default_value' => isset($filter->settings['googtube_method']) ? $filter->settings['googtube_method'] : $defaults['googtube_method'],
    '#options' => $methods,
	'#description'=> t('Method to use in showing the video.'),
  );
  $settings['googtube_width'] = array(
    '#type' => 'textfield',
    '#title' => t('Default width setting'),
    '#default_value' => isset($filter->settings['googtube_width']) ? $filter->settings['googtube_width'] : $defaults['googtube_width'],
    '#maxlength' => 4,
  );
  $settings['googtube_height'] = array(
    '#type' => 'textfield',
    '#title' => t('Default height setting'),
    '#default_value' => isset($filter->settings['googtube_height']) ? $filter->settings['googtube_height'] : $defaults['googtube_height'],
    '#maxlength' => 4,
  );
  $settings['googtube_info_hw'] = array(
    '#type' => 'radios',
    '#title' => t('Use height and width from videoinfo when available'),
    '#description' => t('When available (Vimeo) height and width from videoinfo will be used.'),
    '#default_value' => isset($filter->settings['googtube_info_hw']) ? $filter->settings['googtube_info_hw'] : $defaults['googtube_info_hw'],
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
  );
  $settings['googtube_fs'] = array(
    '#type' => 'radios',
    '#title' => t('Enable fullscreen button'),
    '#default_value' => isset($filter->settings['googtube_fs']) ? $filter->settings['googtube_fs'] : $defaults['googtube_fs'],
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
  );
  $settings['googtube_autoplay'] = array(
    '#type' => 'radios',
    '#title' => t('Default autoplay setting'),
    '#default_value' => isset($filter->settings['googtube_autoplay']) ? $filter->settings['googtube_autoplay'] : $defaults['googtube_autoplay'],
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
  );
  $settings['googtube_rel'] = array(
    '#type' => 'radios',
    '#title' => t('Related videos setting'),
    '#description' => t('Show "related videos"? Not all video formats support this setting.'),
    '#default_value' => isset($filter->settings['googtube_rel']) ? $filter->settings['googtube_rel'] : $defaults['googtube_rel'],
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
  );
  $settings['googtube_removed'] = array(
    '#type' => 'radios',
    '#title' => t('Removed videos setting'),
    '#description' => t('Show removed videos?'),
    '#default_value' => isset($filter->settings['googtube_removed']) ? $filter->settings['googtube_removed'] : $defaults['googtube_removed'],
    '#options' => array(
      0 => t('No'),
      1 => t('Yes'),
    ),
  );
  return $settings;
}

function _googtube_tips($filter, $format, $long = false) {
  return t('Youtube and Vimeo video links are automatically converted into embedded videos.');
}

function _googtube_process($text = '', $filter, $format = -1) {

  //youtube regex
  if (preg_match_all('#(((http://)?)|(^./))(((www.)?)|(^./))youtube\.com/watch[?]v=([^\[\]()<.,\s\n\t\r]+)(?![^<]*</a>)#i', $text, $matches)); {
    foreach ($matches[0] as $mi => $match) {
      $replace = googtube_youtube($match, $filter);
      $text = str_replace($match, $replace, $text);
    };
  }

  //vimeo video regex
  if (preg_match_all('#(((http://)?)|(^./))(((www.)?)|(^./))vimeo\.com/([0-9]+)(?![^<]*</a>)#i', $text, $matches)) {
    foreach ($matches[0] as $mi => $match) {
      $replace = googtube_vimeo($match, $filter);
      $text = str_replace($match, $replace, $text);
    };
  }
  
  return $text;
}

function googtube_youtube($match, $filter) {
  // extract id from complete url
  $parsed_url = parse_url(check_url($match));
  parse_str($parsed_url['query'], $parsed_query);
  $youtube_id = $parsed_query['v'];
  $headers = get_headers("http://gdata.youtube.com/feeds/api/videos/" . $youtube_id);
  // existing video?
  if (preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0])) {
    // existing video
    // load info about video in xml format
    $xmlData = simplexml_load_file("http://gdata.youtube.com/feeds/api/videos/" . $youtube_id);
    // parse video entry
    $video= new stdClass;
    // get nodes in media: namespace for media information
    $media = $xmlData->children('http://search.yahoo.com/mrss/');
    // get video title
    $video->title = $media->group->title;
    // get video description
    $video->description = $media->group->description;
    // get video thumbnail
    $attrs = $media->group->thumbnail[2]->attributes();
    $video->thumbnailURL = $attrs['url'];
    // these variables include the video information
    $videos["title"] = strip_tags(stripslashes($video->title));
    $videos["description"] = strip_tags(str_replace('"', '\'', stripslashes($video->description)));
    $videos["thumbnail"] = stripslashes($video->thumbnailURL);
    } else {
    // non-existing video
    // show removed videos?
	    if ($filter->settings['googtube_removed']) {
      // fill variables with Not available message
        $videos["title"] = t('Not available.');
        $videos["description"] = t('This video has been removed.');
        $videos["thumbnail"] = '/' . drupal_get_path('module', 'googtube') . '/default.jpg';
      } else {
	      // don't show removed video
	      return;
      };
    }
    // construct html for each method
    switch ($filter->settings['googtube_method']) {
      case 'embedded':
        return '<object width="' . $filter->settings['googtube_width'] . '" height="' . $filter->settings['googtube_height'] . '"><param name="movie" value="http://www.youtube.com/v/' . $youtube_id . '?version=3&fs=' . $filter->settings['googtube_fs'] . '&autoplay=' . $filter->settings['googtube_autoplay'] .'&rel=' . $filter->settings['googtube_rel'] . '"></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/' . $youtube_id . '?version=3&fs=' . $filter->settings['googtube_fs'] . '&autoplay=' . $filter->settings['googtube_autoplay'] . '&rel=' . $filter->settings['googtube_rel'] . '" type="application/x-shockwave-flash" wmode="transparent" allowscriptaccess="always" allowfullscreen="true" width="' . $filter->settings['googtube_width'] . '" height="' . $filter->settings['googtube_height'] . '"></embed></object>';
        break;
      case 'iframe':
        return '<iframe class="youtube-video" width="' . $filter->settings['googtube_width'] . '" height="' . $filter->settings['googtube_height'] . '" src="http://www.youtube.com/embed/' . $youtube_id . '?fs=' . $filter->settings['googtube_fs'] . '&autoplay=' . $filter->settings['googtube_autoplay'] . '&rel=' . $filter->settings['googtube_rel'] . '" frameborder="0" allowfullscreen></iframe>';
        break;
      case 'floatbox':
        return '<a href="http://www.youtube.com/embed/' . $youtube_id . '?fs=' . $filter->settings['googtube_fs'] . '&rel=' . $filter->settings['googtube_rel'] . '&hd=1&autoplay=' . $filter->settings['googtube_autoplay'] . '" class="floatbox youtube-video" data-fb-options="width:' . $filter->settings['googtube_width'] . ' height:' . $filter->settings['googtube_height'] . ' autoFitMedia:true"><img title="' . $videos["title"] . ': ' . $videos["description"] . ' ' . t('[CLICK TO PLAY VIDEO]') . '" src="' . $videos["thumbnail"] . '" /></a>';
        break;
  	  case 'colorbox':
  	    return '<a class="colorbox-load youtube-video" href="http://www.youtube.com/embed/' . $youtube_id . '?fs=' . $filter->settings['googtube_fs'] . '&rel=' . $filter->settings['googtube_rel'] . '&hd=1&autoplay='. $filter->settings['googtube_autoplay'] . '&amp;width=' . $filter->settings['googtube_width'] . '&amp;height=' . $filter->settings['googtube_height'] . '&amp;iframe=true&amp;wmode=transparent" title="' . $videos["title"] . ': ' . $videos["description"]  . '"><img title="'  . $videos["title"] . ': ' . $videos["description"] . ' ' . t('[CLICK TO PLAY VIDEO]') . '" src="' . $videos["thumbnail"] . '" /></a>';
        break;
    }
}

function googtube_vimeo($match, $filter) {
  // extract id from complete url
  $parsed_url = parse_url(check_url($match));
  $vimeo_id = substr($parsed_url['path'],strripos($parsed_url['path'],"/")+1);
  $headers = get_headers("http://vimeo.com/api/v2/video/" . $vimeo_id . ".php");
  // existing video?
  if (preg_match('/^HTTP\/\d\.\d\s+(200|301|302)/', $headers[0])) {
    // existing video
    // load info about video
    $videodata = file_get_contents("http://vimeo.com/api/v2/video/" . $vimeo_id . ".php");
    // parse videodata
	  $hash = unserialize($videodata);
    // replace incorrect double hyphens in description by single hyphens (found some video's with these)
    $vimeo_description = strip_tags(str_replace('"', '\'', $hash[0]['description']));
    // set height and width from videoinfo or from settings
    if (variable_get('googtube_info_hw')) {
      $height = $hash[0]['height'];
	    $width  = $hash[0]['width'];
    } else {
      $height = variable_get('googtube_height');
	    $width  = variable_get('googtube_width');
    }
	  $vimeo_title = $hash[0]['title'];
	  $vimeo_thumbnail = $hash[0]['thumbnail_small'];
  } else {
    // non-existing video
	  if ($filter->settings['googtube_removed']) {
      // no: fill variables with Not available message
      $height = variable_get('googtube_height');
  	  $width  = variable_get('googtube_width');
  	  $vimeo_title = t('Not available.');
  	  $vimeo_description = t('This video has been removed.');
  	  $vimeo_thumbnail = '/' . drupal_get_path('module', 'googtube') . '/default.jpg';
    } else {
	    // don't show removed video
	    return;
    };
  }
  // construct html for each method
  switch ($filter->settings['googtube_method']) {
    case 'embedded':
      return '<object width="' . $width . '" height="' . $height . '"><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=' . $vimeo_id . '&amp;server=vimeo.com&amp;show_byline=0&amp;show_portrait=0&amp;autoplay=' . $filter->settings['googtube_autoplay'] . '&amp;fullscreen=' . $filter->settings['googtube_fs'] . '" /></param><param name="wmode" value="transparent"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://vimeo.com/moogaloop.swf?clip_id=' . $vimeo_id . '&amp;server=vimeo.com&amp;show_byline=0&amp;show_portrait=0&amp;fullscreen=' . $filter->settings['googtube_fs'] . '" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="' . $width . '" height="' . $height . '"></embed></object>';
      break;
    case 'iframe':
      return '<iframe class="vimeo-video" width="' . $width . '" height="' . $height . '" src="http://player.vimeo.com/video/' . $vimeo_id . '?fullscreen=' . $filter->settings['googtube_fs'] . '&autoplay=' . $filter->settings['googtube_autoplay'] . '&byline=0&portrait=0" frameborder="0" allowfullscreen></iframe>';
      break;
    case 'floatbox':
      return '<a href="http://player.vimeo.com/video/' . $vimeo_id . '?autoplay=' . $filter->settings['googtube_autoplay'] . '&amp;fullscreen=' . $filter->settings['googtube_fs'] . '&amp;byline=0&amp;portrait=0" class="floatbox vimeo-video" data-fb-options="width:' . $width . ' height:' . $height . ' autoFitMedia:true"><img title="' . $vimeo_title . ': ' . $vimeo_description . ' ' . t('[CLICK TO PLAY VIDEO]') . '"src="' . $vimeo_thumbnail . '" /></a>';
      break;
	case 'colorbox':
      return '<a class="colorbox-load vimeo-video" href="http://player.vimeo.com/video/' . $vimeo_id . '?autoplay=' . $filter->settings['googtube_autoplay'] . '&amp;fullscreen=' . $filter->settings['googtube_fs'] . '&amp;byline=0&amp;portrait=0&amp;width=' . $width . '&amp;height=' . $height . '&amp;iframe=true&amp;wmode=transparent" title="' . $vimeo_title . ': ' . $vimeo_description . '"><img title="' . $vimeo_title . ': ' . $vimeo_description . ' ' . t('[CLICK TO PLAY VIDEO]') . '"src="' . $vimeo_thumbnail . '" /></a>';
      break;
  }
}